package javagames.render;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;

import javagames.util.FrameRate;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class ActiveRenderingExample extends JFrame implements Runnable {
	private volatile boolean running;
	private Thread gameThread;
	private BufferStrategy bs;
	private FrameRate frameRate;
	
	public ActiveRenderingExample() {
		frameRate = new FrameRate();
	}

	protected void createAndShowGUI() { 
		Canvas canvas = new Canvas();
		canvas.setSize(320,240);
		canvas.setBackground(Color.BLACK);
		canvas.setIgnoreRepaint(true);
		getContentPane().add(canvas);
		setTitle("Active Rendering");
		this.setIgnoreRepaint(true);
		pack();
		
		setVisible(true);
		canvas.createBufferStrategy(2);
		bs = canvas.getBufferStrategy();
		
		gameThread = new Thread(this);
		gameThread.start();
	}
	
	@Override
	public void run() {
		running = true;
		frameRate.initialize();
		while(running) {
			gameLoop();
		}
	}
	
	public void gameLoop(){
		do {
			do {
				Graphics g = null;
				try {
					g = bs.getDrawGraphics();
					g.clearRect(0, 0, getWidth(), getHeight());
					render(g);
				} finally {
					if (g!=null){
						g.dispose();
					}
				}
			} while(bs.contentsRestored());
			bs.show();
		} while (bs.contentsLost());
	}
	
	private void render(Graphics g){
		frameRate.calculate();
		g.setColor(Color.GREEN);
		g.drawString(frameRate.getFrameRate(), 30, 30);
		g.drawString(frameRate.getFrameDelta(), 30, 45);
	}
	
	protected void onWindowClosing(){
		try {
			running = false;
			gameThread.join();
		} catch (InterruptedException ex) { 
			ex.printStackTrace();
		}	
		System.exit(0);
	}
	
	public static void main(String[] args){
		final ActiveRenderingExample app = new ActiveRenderingExample();
		app.addWindowListener( new WindowAdapter() { 
			public void windowClosing(WindowEvent e) {
				app.onWindowClosing();
			}
		});
		
		SwingUtilities.invokeLater(new Runnable() {
			public void run(){
				app.createAndShowGUI();
			}	
		});

	}

}
